# image_text.py
"""
给图片（如二维码）添上文字
Usage::
     from xxx import deco_image
    deco_image(image_path, text)  # 替换旧图片
    deco_image(image_path, text, new_path, color='red')  # 保留旧图片并指定文字颜色
"""
from pathlib import Path
from typing import Optional, Tuple, Union
import logging
from PIL import Image, ImageDraw, ImageFont  # pip install pillow
import random
import string

# TIP = "请用微信扫码支付或分享到微信中打开"


# 获取图片宽度
def get_img_width(fname) -> int:
    return Image.open(fname).size[0]


# 获取图片高度
def get_img_height(fname) -> int:
    return Image.open(fname).size[1]


# 给图片加文字
# 生成blank_img空白图片，加上文字之后生成新图片或覆盖旧图, 宽度为origin_img原始图片的宽度

MARGIN_LEFT, MARGIN_TOP = 120, 5
FONT_SIZE = 32
FONT_COLOR = "black"


def gen_text_img(
        origin_img: Union[Path, str],
        text: str,
        img_path=None,
        color=FONT_COLOR,
        font_size: int = FONT_SIZE,
        margin_left: int = MARGIN_LEFT,
        margin_top: int = MARGIN_TOP,
        blank_img=None,
        font_path: Optional[str] = None,
        show_img: bool = False,
) -> Union[Path, str]:
    width = get_img_width(origin_img)
    if blank_img is None:
        blank_img = Path(f"blank-{width}.png")
    elif isinstance(blank_img, str):
        blank_img = Path(blank_img)
    if not blank_img.exists():
        Image.new("RGB", (width, 70), (255, 255, 255)).save(blank_img)
    im = Image.open(blank_img)
    draw = ImageDraw.Draw(im)
    if font_path is None:
         font_path = "Songti.ttc"
        # font_path = "/System/Library/Fonts/Supplemental/Songti.ttc"
        # font_path = "/usr/share/fonts/truetype/windows-font/Songti.ttc"
    fnt = ImageFont.truetype(font_path, font_size)
    draw.text((margin_left, margin_top), text, fill=color, font=fnt)
    if img_path is None:
        img_path = Path(origin_img)
        img_path = img_path.with_name(f"{img_path.stem}-{len(text)}{img_path.suffix}")
    im.save(img_path)
    if show_img:
        im.show()
    return img_path


# 拼接图片，把上面生成的文字图片拼接到原图上面
# 生成一张宽度一致，高度为两张图片之和的空白长图
# 分别打开图片进行粘贴到空白长图里面

def join_imgs(text_img, origin_img, new_path=None) -> None:
    w = get_img_width(text_img)
    fh = get_img_height(text_img)
    oh = get_img_height(origin_img)
    blank_long_img = Image.new("RGB", (w, fh + oh))  # 空白长图
    font_img = Image.open(text_img).resize((w, fh), Image.ANTIALIAS)
    blank_long_img.paste(font_img, (0, oh))

    img1 = Image.open(origin_img).resize((w, oh), Image.ANTIALIAS)
    blank_long_img.paste(img1, (0, 0))

    if new_path is None:
        new_path = origin_img

    blank_long_img.save(new_path)

    out=Image.open(new_path).resize((354,401), Image.ANTIALIAS)
    out.save('vote/'+new_path,dpi=(300.0,300.0))
    # out.show()


def deco_image(
        fpath: Union[Path, str],  # 图片路径
        text: str = '',  # 要添加的文字
        new_path: Union[Path, str, None] = None,  # 新图片要保存的路径（默认覆盖原图）
        color: Union[str, Tuple[int, int, int]] = FONT_COLOR,  # 文字颜色
        font_size: int = FONT_SIZE,  # 文字高度
        margin_left: int = MARGIN_LEFT,
        margin_top: int = MARGIN_TOP,
) -> None:
    text_img = gen_text_img(
        fpath,
        text,
        color=color,
        font_size=font_size,
        margin_left=margin_left,
        margin_top=margin_top,
    )
    join_imgs(text_img, fpath)


